package com.aididi.web;

import com.aididi.common.constant.SystemConstant;
import com.aididi.common.entity.R;
import com.aididi.common.JwtUtil;
import com.aididi.entity.User;
import com.aididi.repository.UserRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName UserController
 * @Description todo
 * @Author xuzexiang
 * @Data 2019/8/21 13:20
 */
@Api(tags = "用户管理")
@RestController
@Slf4j
public class LoginController {

    UserRepository userRepository;

    @Autowired
    public LoginController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @ApiOperation(value = "用户登录")
    @PostMapping(value = "/login")
    public R login(@RequestParam(required = false) String username, @RequestParam(required = false) String password, HttpServletResponse response){
        User user = userRepository.findByUsername(username);
        if(null != user){
            if(user.getPassword().equals(password)){
                //把token返回给客户端-->客户端保存至cookie-->客户端每次请求附带cookie参数
                String jwt = JwtUtil.createJwt("1",username, SystemConstant.JWT_TTL);
                return R.ok(jwt);
            }else {
                return R.error();
            }
        }else {
            return R.error();
        }
    }


    @ApiOperation(value = "获取用户信息",notes = "根据username获取用户信息")
    @ApiImplicitParam(name = "username",value = "用户名",required = true,dataType = "String")
    @PostMapping("/finduser")
    public R getUser(@RequestParam String username){
        User user = userRepository.findByUsername(username);
        return R.ok(user.getDescription());
    }


}
